<template>
  <div class="meeting-room-container">
    <el-card shadow="hover" class="!border-0">
      <template #header>
        <div class="flex items-center justify-between">
          <div>
            <h2 class="text-xl font-semibold text-gray-800">会议室状态总览</h2>
            <p class="text-gray-500 text-sm">实时查看和管理所有会议室状态</p>
          </div>
          <div class="flex items-center gap-4">
            <el-select
              v-model="statusFilter"
              placeholder="筛选状态"
              clearable
              @change="handleStatusFilterChange"
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="空闲" value="AVAILABLE" />
              <el-option label="预定" value="BOOKED" />
              <el-option label="使用中" value="INUSE" />
              <el-option label="锁定" value="LOCKED" />
              <el-option label="维护中" value="MAINTENANCE" />
            </el-select>
            <el-button type="primary" @click="fetchMeetingRooms">
              <el-icon><refresh /></el-icon>
              <span class="ml-1">刷新</span>
            </el-button>
          </div>
        </div>
      </template>

      <!-- 会议室卡片列表 -->
      <div class="room-grid">
        <el-card
          v-for="room in filteredRooms"
          :key="room.id"
          shadow="hover"
          :class="['room-card', getStatusBorderClass(room.status)]"
        >
          <div class="p-4 space-y-3">
            <!-- 会议室标题和状态 -->
            <div class="flex justify-between items-center">
              <h3 class="font-semibold text-lg text-gray-800">{{ room.name }}</h3>
              <el-tag
                :type="getStatusTagType(room.status)"
                effect="light"
                class="!flex items-center gap-1"
              >
                <component :is="getStatusIcon(room.status)" class="h-4 w-4" />
                {{ getStatusText(room.status) }}
              </el-tag>
            </div>

            <!-- 会议室基本信息 -->
            <div class="space-y-2 text-sm text-gray-600">
              <div class="flex items-center">
                <el-icon class="mr-1"><office-building /></el-icon>
                <span>类型: {{ getRoomTypeText(room.type) }}</span>
              </div>
              <div class="flex items-center">
                <el-icon class="mr-1"><user /></el-icon>
                <span>容量: {{ room.seats }}人</span>
              </div>
              <div class="flex items-center">
                <el-icon class="mr-1"><location /></el-icon>
                <span>面积: {{ room.areaSqm !== undefined ? room.areaSqm + '㎡' : '--' }}</span>
              </div>
              <div class="flex items-center">
                <el-icon class="mr-1"><money /></el-icon>
                <span
                  >价格: ¥{{
                    room.pricePerHour !== undefined ? room.pricePerHour.toFixed(2) : '0.00'
                  }}/小时</span
                >
              </div>
            </div>

            <!-- 设备信息 -->
            <div class="space-y-2 pt-2">
              <h4 class="text-sm font-medium text-gray-700">设备配置</h4>
              <div class="flex flex-wrap gap-2">
                <el-tag v-if="room.hasProjector" size="small" type="info">
                  <el-icon class="mr-1"><video-camera /></el-icon>
                  投影仪
                </el-tag>
                <el-tag v-if="room.hasSoundSystem" size="small" type="info">
                  <el-icon class="mr-1"><microphone /></el-icon>
                  音响
                </el-tag>
                <el-tag v-if="room.hasNetwork" size="small" type="info">
                  <el-icon class="mr-1"><connection /></el-icon>
                  网络
                </el-tag>
                <el-tag v-if="room.otherEquipmentDetails" size="small" type="info">
                  <el-icon class="mr-1"><tools /></el-icon>
                  {{ room.otherEquipmentDetails }}
                </el-tag>
              </div>
            </div>

            <!-- 状态操作 -->
            <div class="space-y-2 pt-3">
              <label class="block text-sm font-medium text-gray-700">更新状态</label>
              <el-select
                :value="room.status"
                @change="
                  (value) => {
                    const roomId = room.id || room.room_id || room.roomId
                    if (!roomId) {
                      console.error('无效的会议室ID:', room)
                      ElMessage.error('无法获取会议室ID')
                      return
                    }
                    handleStatusChange(roomId, value)
                  }
                "
                class="w-full"
              >
                <el-option label="空闲" value="AVAILABLE" />
                <el-option label="预定" value="BOOKED" />
                <el-option label="使用中" value="INUSE" />
                <el-option label="锁定" value="LOCKED" />
                <el-option label="维护中" value="MAINTENANCE" />
              </el-select>
            </div>

            <!-- 查看时间段状态按钮 -->
            <div class="pt-3">
              <el-button
                type="primary"
                plain
                @click="showReservationDialog(room.id)"
                class="w-full"
              >
                查看该会议室时间段状态
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <div v-if="filteredRooms.length === 0" class="text-center py-8">
        <el-empty description="没有找到会议室" />
      </div>
    </el-card>

    <!-- 会议室时间段状态对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${currentRoom?.name || ''} 时间段状态（默认显示未来七天状态）`"
      width="800px"
      class="reservation-dialog"
    >
      <div class="space-y-4">
        <!-- 时间筛选 -->
        <div class="flex items-center gap-4 reservation-time-picker">
          <el-date-picker v-model="filterStartTime" type="datetime" placeholder="开始时间" />
          <el-date-picker v-model="filterEndTime" type="datetime" placeholder="结束时间" />
          <el-button @click="fetchRoomReservations">筛选</el-button>
          <el-button @click="clearFilters">清除</el-button>
        </div>

        <!-- 状态表格 -->
        <el-table
          :data="filteredReservations"
          v-loading="loadingReservations"
          :empty-text="getEmptyText()"
        >
          <el-table-column label="开始时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="持续时间" width="120">
            <template #default="{ row }">
              {{ calculateDuration(row.startTime, row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-tag
                  :type="getReservationStatusColor(row.status)"
                  class="reservation-status-tag"
                >
                  {{ getReservationStatusText(row.status) }}
                </el-tag>
                <span v-if="row.message" class="text-gray-500 text-sm ml-2">{{ row.message }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage, ElCard, ElTag, ElSelect, ElOption, ElEmpty, ElButton } from 'element-plus'
import {
  Refresh,
  VideoCamera,
  Microphone,
  Connection,
  OfficeBuilding,
  User,
  Location,
  Money,
  Tools,
} from '@element-plus/icons-vue'
import {
  CheckCircle,
  Clock,
  Building2,
  AlertTriangle,
  Settings,
  CalendarClock,
} from 'lucide-vue-next'

export default {
  name: 'MeetingRoomStatusView',
  components: {
    ElCard,
    ElTag,
    ElSelect,
    ElOption,
    ElEmpty,
    ElButton,
    Refresh,
    VideoCamera,
    Microphone,
    Connection,
    OfficeBuilding,
    User,
    Location,
    Money,
    Tools,
    CheckCircle,
    Clock,
    Building2,
    AlertTriangle,
    Settings,
    CalendarClock,
  },
  data() {
    return {
      meetingRooms: [],
      statusFilter: '',
      loading: false,
      dialogVisible: false,
      currentRoomId: null,
      currentRoom: null, // 添加当前会议室信息
      reservations: [],
      filterStartTime: null,
      filterEndTime: null,
      loadingReservations: false,
    }
  },
  computed: {
    filteredRooms() {
      if (!this.statusFilter) return this.meetingRooms
      return this.meetingRooms.filter((room) => room.status === this.statusFilter)
    },
    filteredReservations() {
      if (!this.filterStartTime && !this.filterEndTime) {
        return this.reservations
      }

      return this.reservations.filter((res) => {
        const resStart = new Date(res.startTime)
        const resEnd = new Date(res.endTime)
        const filterStart = this.filterStartTime ? new Date(this.filterStartTime) : null
        const filterEnd = this.filterEndTime ? new Date(this.filterEndTime) : null

        return (!filterStart || resEnd >= filterStart) && (!filterEnd || resStart <= filterEnd)
      })
    },
  },
  mounted() {
    this.fetchMeetingRooms()
  },
  methods: {
    handleStatusFilterChange(value) {
      this.statusFilter = value
    },

    async fetchMeetingRooms() {
      try {
        this.loading = true
        const response = await axios.get('http://localhost:8080/api/meetingrooms')

        // 处理会议室数据，支持多种ID字段名
        this.meetingRooms = response.data.map(({ id, room_id, roomId, ...rest }) => {
          const actualRoomId = id || room_id || roomId
          if (!actualRoomId) {
            console.error('无效的会议室数据，缺少ID字段:', { id, room_id, roomId, ...rest })
            throw new Error(`会议室 ${rest.name} 缺少ID字段`)
          }
          return {
            id: actualRoomId,
            room_id: actualRoomId,
            roomId: actualRoomId, // 确保所有可能的ID字段都有值
            ...rest,
          }
        })

        console.log('会议室数据加载完成:', this.meetingRooms)
      } catch (error) {
        console.error('获取会议室数据失败:', error)
        ElMessage.error(error.response?.data?.message || '获取会议室数据失败')
      } finally {
        this.loading = false
      }
    },

    async handleStatusChange(roomId, newStatus) {
      try {
        // 确保 roomId 是数字类型，以防万一
        const numericRoomId = Number(roomId)
        if (isNaN(numericRoomId) || !numericRoomId) {
          // 检查是否为有效数字
          console.error('会议室ID无效:', { roomId, newStatus })
          throw new Error('会议室ID无效')
        }

        console.log('更新会议室状态:', { roomId: numericRoomId, newStatus })
        const response = await axios.put(
          `http://localhost:8080/api/meetingrooms/${numericRoomId}/status`,
          { status: newStatus }
        )

        if (response.data) {
          const updatedRoom = response.data
          ElMessage.success(`会议室状态已更新为: ${this.getStatusText(newStatus)}`)

          // 重新获取所有会议室数据以更新本地列表
          this.fetchMeetingRooms()
        }
      } catch (error) {
        console.error('更新状态失败:', error)
        ElMessage.error(error.response?.data?.message || '更新状态失败')
      }
    },

    getStatusTagType(status) {
      const normalizedStatus = status.toUpperCase().replace(/_/g, '') // 规范化状态字符串
      switch (normalizedStatus) {
        case 'AVAILABLE':
          return 'success'
        case 'BOOKED':
          return 'primary'
        case 'INUSE':
          return 'warning' // 保持黄色
        case 'LOCKED':
          return 'info' // 恢复为灰色
        case 'MAINTENANCE':
          return 'danger' // 保持红色
        default:
          return ''
      }
    },

    getStatusBorderClass(status) {
      const normalizedStatus = status.toUpperCase().replace(/_/g, '') // 规范化状态字符串
      switch (normalizedStatus) {
        case 'AVAILABLE':
          return 'border-l-4 border-l-green-400'
        case 'BOOKED':
          return 'border-l-4 border-l-blue-400'
        case 'INUSE':
          return 'border-l-4 border-l-yellow-400' // 保持黄色边框
        case 'LOCKED':
          return 'border-l-4 border-l-gray-400' // 恢复为灰色边框
        case 'MAINTENANCE':
          return 'border-l-4 border-l-red-400' // 保持红色边框
        default:
          return ''
      }
    },

    getStatusIcon(status) {
      const normalizedStatus = status.toUpperCase().replace(/_/g, '') // 规范化状态字符串
      switch (normalizedStatus) {
        case 'AVAILABLE':
          return CheckCircle
        case 'BOOKED':
          return Clock
        case 'INUSE':
          return Building2
        case 'LOCKED':
          return AlertTriangle
        case 'MAINTENANCE':
          return Settings
        default:
          return null
      }
    },

    getStatusText(status) {
      const normalizedStatus = status.toUpperCase().replace(/_/g, '') // 规范化状态字符串
      switch (normalizedStatus) {
        case 'AVAILABLE':
          return '空闲'
        case 'BOOKED':
          return '预定'
        case 'INUSE':
          return '使用中'
        case 'LOCKED':
          return '锁定'
        case 'MAINTENANCE':
          return '维护中'
        default:
          return status // 返回原始状态，如果无法匹配
      }
    },

    getRoomTypeText(type) {
      switch (type) {
        case 'CLASSROOM_STYLE':
          return '教室型'
        case 'ROUND_TABLE_STYLE':
          return '圆桌型'
        default:
          return type
      }
    },

    async showReservationDialog(roomId) {
      this.currentRoomId = roomId
      // 获取当前会议室信息
      this.currentRoom = this.meetingRooms.find((room) => room.id === roomId)
      this.dialogVisible = true

      // 设置默认时间范围为当前时间到未来7天
      const now = new Date()
      const nextWeek = new Date()
      nextWeek.setDate(now.getDate() + 7)

      this.filterStartTime = now
      this.filterEndTime = nextWeek
      await this.fetchRoomReservations()
    },

    async fetchRoomReservations() {
      try {
        this.loadingReservations = true
        const response = await axios.get(
          `http://localhost:8080/api/meetingrooms/${this.currentRoomId}/reservations`
        )

        let sortedReservations = response.data.sort(
          (a, b) => new Date(a.startTime) - new Date(b.startTime)
        )

        // 如果没有预约数据，添加一个从现在到未来7天的空闲时段
        if (sortedReservations.length === 0) {
          const now = new Date()
          const nextWeek = new Date()
          nextWeek.setDate(now.getDate() + 7)

          this.reservations = [
            {
              startTime: now.toISOString(),
              endTime: nextWeek.toISOString(),
              status: 'AVAILABLE',
              id: 'free-default',
              message: '未来七天内暂无预约',
            },
          ]
          return
        }

        let allTimeSlots = []
        for (let i = 0; i < sortedReservations.length; i++) {
          const current = sortedReservations[i]
          allTimeSlots.push(current)
          if (i < sortedReservations.length - 1) {
            const next = sortedReservations[i + 1]
            const currentEnd = new Date(current.endTime)
            const nextStart = new Date(next.startTime)
            if (currentEnd < nextStart) {
              allTimeSlots.push({
                startTime: current.endTime,
                endTime: next.startTime,
                status: 'AVAILABLE',
                id: `free-${i}`,
              })
            }
          }
        }

        this.reservations = allTimeSlots
      } catch (error) {
        console.error('获取会议室订单失败:', error)
        ElMessage.error('获取会议室订单失败')
      } finally {
        this.loadingReservations = false
      }
    },

    getReservationStatusText(status) {
      switch (status) {
        case 'CANCELLATION_REQUESTED':
        case 'CONFIRMED':
          return '预定中'
        case 'PENDING_PAYMENT':
          return '锁定中'
        case 'IN_USE':
          return '使用中'
        case 'AVAILABLE':
          return '空闲中'
        default:
          return status
      }
    },

    getReservationStatusColor(status) {
      switch (status) {
        case 'CANCELLATION_REQUESTED':
        case 'CONFIRMED':
          return 'primary'
        case 'PENDING_PAYMENT':
          return 'info'
        case 'IN_USE':
          return 'warning'
        case 'AVAILABLE':
          return 'success'
        default:
          return ''
      }
    },

    formatDateTime(dateString) {
      const date = new Date(dateString)
      const now = new Date()

      // 如果是今天，只显示时间
      if (date.toDateString() === now.toDateString()) {
        return `今天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
      }

      // 否则显示完整日期时间
      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
        })
        .replace(/\//g, '-')
    },

    calculateDuration(startTime, endTime) {
      const start = new Date(startTime)
      const end = new Date(endTime)
      const diff = end - start

      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

      if (hours > 0 && minutes > 0) {
        return `${hours}小时${minutes}分钟`
      } else if (hours > 0) {
        return `${hours}小时`
      } else {
        return `${minutes}分钟`
      }
    },

    clearFilters() {
      // 清除筛选时重置为默认时间范围（当前时间到未来7天）
      const now = new Date()
      const nextWeek = new Date()
      nextWeek.setDate(now.getDate() + 7)

      this.filterStartTime = now
      this.filterEndTime = nextWeek
      this.fetchRoomReservations()
    },

    getEmptyText() {
      if (this.loadingReservations) {
        return '加载中...'
      }
      return '该会议室未来七天及以后都处于空闲状态'
    },
  },
}
</script>

<style scoped>
.meeting-room-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.room-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 1.5rem;
  padding: 1rem;
}

.room-card {
  height: 100%;
  transition: all 0.3s ease;
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.room-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 卡片内容样式 */
.card-content {
  padding: 1.25rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.room-name {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
}

/* 基本信息样式 */
.info-section {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin: 1rem 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #4b5563;
}

/* 设备信息样式 */
.equipment-section {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #e5e7eb;
}

.equipment-title {
  font-size: 0.875rem;
  font-weight: 500;
  color: #374151;
  margin-bottom: 0.75rem;
}

.equipment-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

/* 状态操作区域样式 */
.status-section {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #e5e7eb;
}

.status-label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #374151;
  margin-bottom: 0.5rem;
}

/* 对话框样式 */
.reservation-dialog {
  max-width: 800px;
  width: 100%;
}

:deep(.el-dialog__body) {
  padding: 1.5rem;
}

:deep(.el-dialog__header) {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-dialog__footer) {
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e7eb;
}

/* 时间选择器样式 */
.reservation-time-picker {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

:deep(.el-date-picker) {
  width: 200px;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 0.5rem;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8fafc;
  font-weight: 600;
}

/* 状态标签样式 */
.reservation-status-tag {
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
}

/* 响应式布局 */
@media (max-width: 1280px) {
  .room-grid {
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  }
}

@media (max-width: 768px) {
  .room-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }

  .reservation-time-picker {
    flex-direction: column;
  }
}

/* 强制覆盖Element Plus样式 */
:deep(.el-card) {
  border: none !important;
  height: 100%;
}

:deep(.el-card__header) {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-card__body) {
  padding: 1.5rem;
}

/* 边框样式 */
.border-l-4 {
  border-left-width: 4px;
  border-left-style: solid;
}
</style>
